//
//  ComboViewFlowLayout.m
//  Project two framework
//
//  Created by rimi on 16/7/25.
//  Copyright © 2016年 张峥. All rights reserved.
//

#import "ComboViewFlowLayout.h"

@implementation ComboViewFlowLayout

-(instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}
//当collectionView视图位置有新改变(发生移动)时调用，其若返回YES则重新布局
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{

    return YES;
}

-(void)prepareLayout{
    [super prepareLayout];
    //设置水平混动
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //设置内边距
    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width)*0.5;
    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
    
}

//写一个方法返回值为一个数组，返回的值决定了所有元素的排版
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    //先获取super 计算好的布局属性
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    //计算集合视图中心的x值
    CGFloat collecctionCenterX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
    //再调整坐标
    for (UICollectionViewLayoutAttributes *attributes in array) {
        //计算cell的中心点
        CGFloat cellX = attributes.center.x;
        //计算集合视图的中心点x的值 和 cell 中心点 x 之间的距离
        CGFloat  centerCell = ABS(cellX-collecctionCenterX);
        //根据间距计算 cell的缩放比例
        CGFloat scale = 1 - centerCell/self.collectionView.frame.size.width;
        //设置缩放比例
        attributes.transform = CGAffineTransformMakeScale(scale, scale);
        
    }
    
    
    
    return array;
}

//设定colletionView停止滚动时的偏移量
-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
    //首先计算出最终显示的形状
    CGRect rect;
    rect.origin.x = proposedContentOffset.x;
    rect.origin.y = 0;
    rect.size = self.collectionView.frame.size;
    
    //获取滚动结束后super计算好的位子
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    //计算colletionView中心x 的值
    CGFloat collectionCenterX = self.collectionView.frame.size.width * 0.5 + proposedContentOffset.x;
    //存放最小的间距
    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attributes in array) {
        if (ABS(minDelta)>ABS(attributes.center.x - collectionCenterX)) {
            minDelta = attributes.center.x - collectionCenterX;
        }
    }
    //修改所有的偏移量
    proposedContentOffset.x += minDelta;
    return proposedContentOffset;
}









@end
